<template>
  <div class="product-storage-add-page">
    <el-card shadow="never" class="breadcrumb-card">
      <div class="breadcrumb-content">
        <div class="breadcrumb-title">
          <el-icon class="breadcrumb-icon">
            <Box />
          </el-icon>
          <div>
            <p class="breadcrumb-subtitle">仓库管理 · 产品入库</p>
            <h2 class="breadcrumb-heading">
              {{ isEditMode ? "编辑产品入库" : "新增产品入库" }}
            </h2>
          </div>
        </div>
        <el-breadcrumb :separator-icon="ArrowRight">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>仓库管理</el-breadcrumb-item>
          <el-breadcrumb-item :to="{ path: '/ProductStorageList' }">
            产品入库
          </el-breadcrumb-item>
          <el-breadcrumb-item>
            {{ isEditMode ? "编辑" : "新增" }}
          </el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </el-card>

    <el-card shadow="never" class="form-card">
      <div class="page-header">
        <div class="page-header__content">
          <div class="page-header__title">
            <div class="page-header__icon-wrapper">
              <el-icon class="page-header__icon"><DocumentAdd /></el-icon>
            </div>
            <div class="page-header__text">
              <h2>{{ pageTitle }}</h2>
              <p class="page-header__desc">
                {{ isEditMode ? "修改产品入库单信息" : "创建新的产品入库单" }}
              </p>
            </div>
          </div>
          <el-tag
            :type="isEditMode ? 'warning' : 'success'"
            effect="dark"
            size="large"
            class="page-header__tag"
          >
            <el-icon class="tag-icon"><Box /></el-icon>
            {{ isEditMode ? "编辑模式" : "新增模式" }}
          </el-tag>
        </div>
      </div>

      <el-form
        ref="formRef"
        :model="formModel"
        :rules="rules"
        label-width="120px"
        class="product-storage-form"
      >
        <div class="form-section">
          <div class="section-header">
            <div class="section-header__main">
              <div class="section-header__icon">
                <el-icon><DocumentAdd /></el-icon>
              </div>
              <div>
                <p class="section-title">基础信息</p>
                <p class="section-subtitle">完善产品入库单的基础内容</p>
              </div>
            </div>
            <el-tag type="success" effect="light" size="small">
              必填字段
            </el-tag>
          </div>

          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="入库单编号" prop="inboundOrderNo" required>
                <div class="system-code-field">
                  <el-input
                    v-model="formModel.inboundOrderNo"
                    placeholder="请输入/自动生成"
                    clearable
                    class="system-code-input"
                    :disabled="autoGenerateEnabled"
                    @input="handleManualInput"
                  >
                    <template #prefix>
                      <el-icon class="system-code-prefix"><Tickets /></el-icon>
                    </template>
                  </el-input>
                  <div class="system-code-switch-wrapper">
                    <span class="switch-label">自动生成</span>
                    <el-switch
                      v-model="autoGenerateEnabled"
                      :active-text="autoGenerateEnabled ? '开启' : '关闭'"
                      :inactive-text="autoGenerateEnabled ? '开启' : '关闭'"
                      active-color="#4facfe"
                      inactive-color="#dcdfe6"
                      @change="handleAutoGenerateChange"
                      class="system-code-switch"
                    />
                  </div>
                </div>
                <div v-if="autoGenerateEnabled" class="auto-generate-hint">
                  <el-icon class="hint-icon"><InfoFilled /></el-icon>
                  <span>已开启自动生成，每次打开开关将生成新的编码</span>
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入库单名称" prop="inboundOrderName" required>
                <el-input
                  v-model="formModel.inboundOrderName"
                  placeholder="请输入"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="入库日期" prop="inboundDate">
                <el-date-picker
                  v-model="formModel.inboundDate"
                  type="date"
                  placeholder="请选择日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入库状态" prop="stats">
                <el-select v-model="formModel.stats" placeholder="请选择">
                  <el-option label="待入库" :value="0" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <el-col :span="12">
              <el-form-item label="生产工单名称" prop="workOrderName" required>
                <el-input
                  v-model="formModel.workOrderName"
                  placeholder="请输入"
                  clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="生产工单编号" prop="workOrderNo">
                <el-input
                  v-model="formModel.workOrderNo"
                  placeholder="请输入"
                  clearable
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input
                  v-model="formModel.remark"
                  type="textarea"
                  :rows="3"
                  placeholder="请输入备注"
                  maxlength="300"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div class="form-section detail-section">
          <div class="section-header">
            <div class="section-header__main">
              <div class="section-header__icon section-header__icon--detail">
                <el-icon><List /></el-icon>
              </div>
              <div>
                <p class="section-title">入库明细</p>
                <p class="section-subtitle">添加产品入库的明细信息</p>
              </div>
            </div>
            <div class="section-header__actions">
              <el-tag type="info" effect="light" size="small">
                共 {{ formModel.detail.length }} 项
              </el-tag>
              <el-button
                type="primary"
                :icon="Plus"
                size="default"
                @click="handleAddDetail"
              >
                添加明细
              </el-button>
            </div>
          </div>

          <el-alert
            v-if="detailError"
            type="error"
            show-icon
            :closable="false"
            class="detail-alert"
          >
            {{ detailError }}
          </el-alert>

          <div v-if="formModel.detail.length" class="detail-list">
            <div
              v-for="(item, index) in formModel.detail"
              :key="index"
              class="detail-item"
            >
              <div class="detail-item-header">
                <div class="detail-item-number-wrapper">
                  <span class="detail-item-number">明细 {{ index + 1 }}</span>
                </div>
                <el-button
                  type="danger"
                  link
                  size="small"
                  :icon="Delete"
                  @click="handleRemoveDetail(index)"
                  >删除</el-button
                >
              </div>
              <el-row :gutter="16">
                <el-col :span="12">
                  <el-form-item label="产品名称" required>
                    <el-input
                      v-model="item.productName"
                      placeholder="请输入"
                      clearable
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="产品编号" required>
                    <el-input
                      v-model="item.productNo"
                      placeholder="请输入"
                      clearable
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="16">
                <el-col :span="12">
                  <el-form-item label="规格型号">
                    <el-input
                      v-model="item.specification"
                      placeholder="请输入"
                      clearable
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="产品类型" required>
                    <el-select
                      v-model="item.productTypeId"
                      placeholder="请选择产品类型"
                      class="product-type-select"
                      popper-class="product-type-dropdown"
                      clearable
                    >
                      <el-option
                        v-for="option in PRODUCT_TYPE_OPTIONS"
                        :key="option.value"
                        :label="option.label"
                        :value="option.value"
                      >
                        <div class="product-type-option">
                          <span class="dot" />
                          <span>{{ option.label }}</span>
                        </div>
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="16">
                <el-col :span="12">
                  <el-form-item label="单位">
                    <el-input
                      v-model="item.unit"
                      placeholder="请输入"
                      clearable
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="批次号" required>
                    <div class="batch-select-field">
                      <el-input
                        v-model="item.batchNo"
                        placeholder="请选择批次号"
                        clearable
                      />
                      <el-button
                        type="primary"
                        link
                        class="batch-select-btn"
                        @click="handleOpenBatchDialog(index)"
                      >
                        <el-icon><Grid /></el-icon>
                        选择
                      </el-button>
                    </div>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="16">
                <el-col :span="12">
                  <el-form-item label="入库数量" required>
                    <el-input-number
                      v-model="item.inboundQuantity"
                      :min="0"
                      :precision="0"
                      controls-position="right"
                      class="full-width"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="仓库负责人">
                    <el-input
                      v-model="item.warehousePrincipal"
                      placeholder="通过选择仓库自动带出"
                      readonly
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="16">
                <el-col :span="12">
                  <el-form-item label="生产日期">
                    <el-date-picker
                      v-model="item.productionDate"
                      type="date"
                      placeholder="请选择日期"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="到期日期">
                    <el-date-picker
                      v-model="item.expiryDate"
                      type="date"
                      placeholder="请选择日期"
                      format="YYYY-MM-DD"
                      value-format="YYYY-MM-DD"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
              </el-row>

              <el-form-item label="仓库名称">
                <div class="warehouse-select-field">
                  <el-input
                    v-model="item.warehouseName"
                    placeholder="请选择仓库/库区/库位"
                    readonly
                    clearable
                  />
                  <el-button
                    type="primary"
                    link
                    class="warehouse-select-btn"
                    @click="handleOpenWarehouseDialog(index)"
                  >
                    <el-icon><Grid /></el-icon>
                    选择
                  </el-button>
                </div>
              </el-form-item>
            </div>
          </div>
        </div>

        <div class="form-actions">
          <el-button @click="handleCancel">取消</el-button>
          <el-button
            type="primary"
            :loading="submitting"
            @click="handleSubmit"
            >{{ isEditMode ? "保存修改" : "提交入库单" }}</el-button
          >
        </div>
      </el-form>
    </el-card>

    <!-- 批次选择对话框 -->
    <el-dialog
      v-model="batchDialogVisible"
      title="选择批次号"
      width="1000px"
      class="batch-dialog"
      :close-on-click-modal="false"
    >
      <div class="batch-dialog-toolbar">
        <el-input
          v-model="batchSearchCode"
          placeholder="请输入批次号"
          clearable
          @keyup.enter="handleBatchSearch"
        />
        <el-button type="primary" @click="handleBatchSearch">查询</el-button>
        <el-button @click="handleBatchReset">重置</el-button>
      </div>
      <el-table
        :data="batchTableData"
        v-loading="batchListLoading"
        height="360"
        border
        class="batch-dialog-table"
        style="width: 1000px"
      >
        <el-table-column width="60" align="center">
          <template #default="{ row }">
            <el-radio
              v-model="selectedBatchId"
              :label="row.id"
              @change="() => handleBatchRowSelect(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="序号" width="80" align="center">
          <template #default="{ $index }">
            {{
              $index +
              1 +
              (batchPagination.pageIndex - 1) * batchPagination.pageSize
            }}
          </template>
        </el-table-column>
        <el-table-column prop="batchCode" label="批次号" min-width="140" />
        <el-table-column label="生产日期" min-width="140">
          <template #default="{ row }">
            {{ formatBatchDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="到期日期" min-width="140">
          <template #default="{ row }">
            {{ formatBatchDate(row.endTime) }}
          </template>
        </el-table-column>
        <el-table-column label="库存" width="100" align="center">
          <template #default="{ row }">
            {{ row.inventory ?? "-" }}
          </template>
        </el-table-column>
      </el-table>
      <div class="batch-dialog-pagination">
        <el-pagination
          background
          layout="prev, pager, next, jumper, ->, total"
          :current-page="batchPagination.pageIndex"
          :page-size="batchPagination.pageSize"
          :total="batchPagination.total"
          @current-change="handleBatchPageChange"
        />
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="batchDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleBatchConfirm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 仓库选择对话框 -->
    <el-dialog
      v-model="warehouseDialogVisible"
      title="选择仓库"
      width="1000px"
      class="warehouse-dialog"
      :close-on-click-modal="false"
    >
      <div class="warehouse-dialog-summary">
        仓库名称：{{ selectedWarehouseOption?.name || "未选择" }}　 库区名称：{{
          selectedReservoirOption?.name || "未选择"
        }}　 库位名称：{{ selectedSeatOption?.name || "未选择" }}
      </div>
      <div class="warehouse-dialog-columns">
        <div class="warehouse-column">
          <div class="column-title">仓库名称</div>
          <el-input
            v-model="warehouseSearchForm.warehouse"
            placeholder="请输入仓库名称"
            clearable
            @keyup.enter="handleWarehouseSearchSubmit('warehouse')"
          >
            <template #suffix>
              <el-icon
                class="column-search-icon"
                @click.stop="handleWarehouseSearchSubmit('warehouse')"
              >
                <Search />
              </el-icon>
            </template>
          </el-input>
          <el-scrollbar class="column-list">
            <div
              v-for="item in warehouseOptions"
              :key="item.id"
              :class="[
                'column-option',
                { active: selectedWarehouseId === item.id },
              ]"
              @click="selectWarehouseOption(item)"
            >
              {{ item.name }}
            </div>
            <el-empty
              v-if="!warehouseOptions.length && !warehouseLoading"
              description="暂无数据"
              :image-size="60"
            />
          </el-scrollbar>
        </div>
        <div class="warehouse-column">
          <div class="column-title">库区名称</div>
          <el-input
            v-model="warehouseSearchForm.reservoir"
            placeholder="请输入库区名称"
            clearable
            @keyup.enter="handleWarehouseSearchSubmit('reservoir')"
          >
            <template #suffix>
              <el-icon
                class="column-search-icon"
                @click.stop="handleWarehouseSearchSubmit('reservoir')"
              >
                <Search />
              </el-icon>
            </template>
          </el-input>
          <el-scrollbar class="column-list">
            <div
              v-for="item in reservoirOptions"
              :key="item.id"
              :class="[
                'column-option',
                { active: selectedReservoirId === item.id },
              ]"
              @click="selectReservoirOption(item)"
            >
              {{ item.name }}
            </div>
            <el-empty
              v-if="!reservoirOptions.length && !reservoirLoading"
              description="暂无数据"
              :image-size="60"
            />
          </el-scrollbar>
        </div>
        <div class="warehouse-column">
          <div class="column-title">库位名称</div>
          <el-input
            v-model="warehouseSearchForm.seat"
            placeholder="请输入库位名称"
            clearable
            @keyup.enter="handleWarehouseSearchSubmit('seat')"
          >
            <template #suffix>
              <el-icon
                class="column-search-icon"
                @click.stop="handleWarehouseSearchSubmit('seat')"
              >
                <Search />
              </el-icon>
            </template>
          </el-input>
          <el-scrollbar class="column-list">
            <div
              v-for="item in seatOptions"
              :key="item.id"
              :class="['column-option', { active: selectedSeatId === item.id }]"
              @click="selectSeatOption(item)"
            >
              {{ item.name }}
            </div>
            <el-empty
              v-if="!seatOptions.length && !seatLoading"
              description="暂无数据"
              :image-size="60"
            />
          </el-scrollbar>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="warehouseDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleWarehouseConfirm"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {
  ArrowRight,
  Box,
  DocumentAdd,
  List,
  Delete,
  Plus,
  Refresh,
  Tickets,
  InfoFilled,
  Grid,
  Search,
} from "@element-plus/icons-vue";
import { computed, onMounted, reactive, ref } from "vue";
import { ElMessage } from "element-plus";
import { useRoute, useRouter } from "vue-router";
import https from "@/Http/http";
import moment from "moment";
import type { FormInstance, FormRules } from "element-plus";

const router = useRouter();
const route = useRoute();

interface ProductDetailForm {
  id: number | null;
  productName: string;
  productNo: string;
  specification?: string;
  productTypeId: number | null;
  unit?: string;
  batchNo?: string;
  inboundQuantity: number | null;
  productionDate?: string | null;
  expiryDate?: string | null;
  warehouseName?: string;
  warehousePrincipal?: string;
}

const formRef = ref<FormInstance>();
const submitting = ref(false);
const isEditMode = ref(false);
const detailError = ref("");
const autoGenerateEnabled = ref(false);
const isAutoGenerated = ref(false);

const PRODUCT_TYPE_OPTIONS = [
  { label: "成品", value: 1 },
  { label: "半成品", value: 2 },
  { label: "其他", value: 3 },
] as const;

// 批次选择相关
const batchDialogVisible = ref(false);
const batchListLoading = ref(false);
const batchTableData = ref<any[]>([]);
const batchSearchCode = ref("");
const batchPagination = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0,
});
const selectedBatchId = ref<number | null>(null);
const selectedBatchRow = ref<any | null>(null);
const currentBatchDetailIndex = ref<number | null>(null);

// 仓库选择相关
const warehouseDialogVisible = ref(false);
const warehouseOptions = ref<any[]>([]);
const reservoirOptions = ref<any[]>([]);
const seatOptions = ref<any[]>([]);
const warehouseSearchForm = reactive({
  warehouse: "",
  reservoir: "",
  seat: "",
});
const selectedWarehouseId = ref<number | null>(null);
const selectedReservoirId = ref<number | null>(null);
const selectedSeatId = ref<number | null>(null);
const selectedWarehouseOption = ref<any | null>(null);
const selectedReservoirOption = ref<any | null>(null);
const selectedSeatOption = ref<any | null>(null);
const currentWarehouseDetailIndex = ref<number | null>(null);
const warehouseLoading = ref(false);
const reservoirLoading = ref(false);
const seatLoading = ref(false);

const formModel = reactive({
  id: null as number | null,
  inboundOrderNo: "",
  inboundOrderName: "",
  inboundDate: moment().format("YYYY-MM-DD"),
  workOrderName: "",
  workOrderNo: "",
  stats: 0,
  remark: "",
  detail: [] as ProductDetailForm[],
});

const rules: FormRules = {
  inboundOrderNo: [
    { required: true, message: "请输入入库单编号", trigger: "blur" },
  ],
  inboundOrderName: [
    { required: true, message: "请输入入库单名称", trigger: "blur" },
  ],
  workOrderName: [
    { required: true, message: "请输入生产工单名称", trigger: "blur" },
  ],
};

const pageTitle = computed(() =>
  isEditMode.value ? "编辑产品入库" : "新增产品入库"
);

const defaultDetail = (): ProductDetailForm => ({
  id: null,
  productName: "",
  productNo: "",
  specification: "",
  productTypeId: null,
  unit: "",
  batchNo: "",
  inboundQuantity: null,
  productionDate: null,
  expiryDate: null,
  warehouseName: "",
  warehousePrincipal: "",
});

const generateCode = () => {
  // 生成基于年月日时分秒的编码，格式：PS + YYYYMMDDHHmmss + 3位随机数
  const timestamp = moment().format("YYYYMMDDHHmmss");
  const random = Math.floor(Math.random() * 1000)
    .toString()
    .padStart(3, "0");
  return `PS${timestamp}${random}`;
};

const handleManualInput = () => {
  // 用户手动输入时，标记为非自动生成
  if (!autoGenerateEnabled.value) {
    isAutoGenerated.value = false;
  }
};

const handleAutoGenerateChange = (value: boolean) => {
  if (value) {
    // 开关打开，生成新编码（每次打开都生成不同的编码）
    formModel.inboundOrderNo = generateCode();
    isAutoGenerated.value = true;
  } else {
    // 开关关闭，如果是自动生成的编码则清除，手动输入的保留
    if (isAutoGenerated.value) {
      formModel.inboundOrderNo = "";
      isAutoGenerated.value = false;
    }
  }
};

// 保留原有的生成函数，用于编辑模式下的兼容
const handleGenerateCode = () => {
  formModel.inboundOrderNo = generateCode();
  isAutoGenerated.value = true;
};

const handleAddDetail = () => {
  formModel.detail.push(defaultDetail());
  detailError.value = "";
};

const handleRemoveDetail = (index: number) => {
  formModel.detail.splice(index, 1);
};

const validateDetails = () => {
  if (!formModel.detail.length) {
    detailError.value = "请至少添加一条入库明细";
    return false;
  }
  for (const [idx, item] of formModel.detail.entries()) {
    if (!item.productName || !item.productNo) {
      detailError.value = `明细 ${idx + 1} 的产品名称与编号不能为空`;
      return false;
    }
    if (
      item.productTypeId === null ||
      item.productTypeId === undefined ||
      item.productTypeId === 0
    ) {
      detailError.value = `明细 ${idx + 1} 的产品类型不能为空`;
      return false;
    }
    if (!item.batchNo) {
      detailError.value = `明细 ${idx + 1} 的批次号不能为空`;
      return false;
    }
    if (!item.inboundQuantity || item.inboundQuantity <= 0) {
      detailError.value = `明细 ${idx + 1} 的入库数量必须大于0`;
      return false;
    }
  }
  detailError.value = "";
  return true;
};

const buildPayload = () => {
  return {
    id: formModel.id,
    inboundOrderNo: formModel.inboundOrderNo.trim(),
    inboundOrderName: formModel.inboundOrderName.trim(),
    inboundDate: formModel.inboundDate,
    workOrderName: formModel.workOrderName.trim(),
    workOrderNo: formModel.workOrderNo?.trim() ?? "",
    stats: formModel.stats,
    remark: formModel.remark?.trim() ?? "",
    detail: formModel.detail.map((item) => ({
      id: item.id,
      productName: item.productName.trim(),
      productNo: item.productNo.trim(),
      specification: item.specification?.trim() ?? "",
      productTypeId: item.productTypeId ?? 0,
      unit: item.unit?.trim() ?? "",
      batchNo: item.batchNo?.trim() ?? "",
      inboundQuantity: item.inboundQuantity ?? 0,
      productionDate: item.productionDate || null,
      expiryDate: item.expiryDate || null,
      warehouseName: item.warehouseName?.trim() ?? "",
      warehousePrincipal: item.warehousePrincipal?.trim() ?? "",
    })),
  };
};

const handleSubmit = async () => {
  if (!formRef.value) return;
  await formRef.value.validate();
  if (!validateDetails()) {
    ElMessage.error(detailError.value || "请检查入库明细");
    return;
  }
  const payload = buildPayload();
  submitting.value = true;
  const request = isEditMode.value
    ? https.Writes.put("/Warehouse/ProductStorageUpdate", payload)
    : https.Writes.post("/Warehouse/ProductStorageAdd", payload);

  request
    .then((res: any) => {
      if ((res.data?.code ?? res.data?.Code) === 1) {
        ElMessage.success(res.data?.msg ?? "操作成功");
        router.push("/ProductStorageList");
      } else {
        throw new Error(res.data?.msg ?? "操作失败");
      }
    })
    .catch((error: any) => {
      console.error("提交产品入库失败:", error);
      const msg =
        error?.message ?? error?.response?.data?.msg ?? "提交失败，请稍后重试";
      ElMessage.error(msg);
    })
    .finally(() => {
      submitting.value = false;
    });
};

const handleCancel = () => {
  router.push("/ProductStorageList");
};

const initializeFromRoute = () => {
  const { editData } = route.query;
  if (!editData) {
    // 新增模式：默认开启自动生成
    autoGenerateEnabled.value = true;
    formModel.inboundOrderNo = generateCode();
    isAutoGenerated.value = true;
    handleAddDetail();
    return;
  }

  try {
    const decoded = decodeURIComponent(editData as string);
    const parsed = JSON.parse(decoded);
    isEditMode.value = true;
    formModel.id = parsed.id ?? null;
    formModel.inboundOrderNo = parsed.inboundOrderNo ?? "";
    // 编辑模式下，如果已有编码，默认关闭自动生成
    autoGenerateEnabled.value = false;
    isAutoGenerated.value = false;
    formModel.inboundOrderName = parsed.inboundOrderName ?? "";
    formModel.inboundDate = parsed.inboundDate || moment().format("YYYY-MM-DD");
    formModel.workOrderName = parsed.workOrderName ?? "";
    formModel.workOrderNo = parsed.workOrderNo ?? "";
    formModel.stats = parsed.stats ?? 0;
    formModel.remark = parsed.remark ?? "";
    formModel.detail =
      Array.isArray(parsed.detail) && parsed.detail.length
        ? parsed.detail.map((item: any) => ({
            id: item.id ?? null,
            productName: item.productName ?? "",
            productNo: item.productNo ?? "",
            specification: item.specification ?? "",
            productTypeId: item.productTypeId ?? null,
            unit: item.unit ?? "",
            batchNo: item.batchNo ?? "",
            inboundQuantity: item.inboundQuantity ?? null,
            productionDate: item.productionDate ?? null,
            expiryDate: item.expiryDate ?? null,
            warehouseName: item.warehouseName ?? "",
            warehousePrincipal: item.warehousePrincipal ?? "",
          }))
        : [defaultDetail()];
  } catch (error) {
    console.error("解析编辑数据失败:", error);
    ElMessage.warning("编辑参数异常，已切换为新增模式");
    isEditMode.value = false;
    formModel.id = null;
    autoGenerateEnabled.value = true;
    formModel.inboundOrderNo = generateCode();
    isAutoGenerated.value = true;
    formModel.detail = [defaultDetail()];
  }
};

// 批次相关函数
const formatBatchDate = (value: string | null | undefined): string | null => {
  if (typeof value !== "string" || !value) return null;
  const [datePart] = value.split("T");
  return datePart ?? null;
};

const normalizeBatchItem = (item: any) => ({
  id: item.id ?? item.Id ?? 0,
  batchCode: item.batchCode ?? item.BatchCode ?? "",
  createTime: item.createTime ?? item.CreateTime ?? null,
  endTime: item.endTime ?? item.EndTime ?? null,
  inventory: item.inventory ?? item.Inventory ?? null,
});

const fetchBatchList = async () => {
  batchListLoading.value = true;
  try {
    const params: Record<string, any> = {
      PageIndex: batchPagination.pageIndex,
      PageSize: batchPagination.pageSize,
    };
    if (batchSearchCode.value.trim()) {
      params.BatchCode = batchSearchCode.value.trim();
    }
    const res = await https.Reads.get("/Warehouse/BatchList", { params });
    const payload = res.data || {};
    const rawList = payload.data ?? payload.Data ?? [];
    batchTableData.value = Array.isArray(rawList)
      ? rawList.map((item: any) => normalizeBatchItem(item))
      : [];
    batchPagination.total =
      payload.totalCount ?? payload.TotalCount ?? batchTableData.value.length;
  } catch (error: any) {
    console.error("获取批次列表失败", error);
    const msg =
      error?.response?.data?.msg ||
      error?.message ||
      "获取批次列表失败，请稍后再试";
    ElMessage.error(msg);
    batchTableData.value = [];
    batchPagination.total = 0;
  } finally {
    batchListLoading.value = false;
  }
};

const handleOpenBatchDialog = (detailIndex: number) => {
  currentBatchDetailIndex.value = detailIndex;
  batchDialogVisible.value = true;
  selectedBatchId.value = null;
  selectedBatchRow.value = null;
  batchPagination.pageIndex = 1;
  fetchBatchList();
};

const handleBatchSearch = () => {
  batchPagination.pageIndex = 1;
  fetchBatchList();
};

const handleBatchReset = () => {
  batchSearchCode.value = "";
  handleBatchSearch();
};

const handleBatchPageChange = (page: number) => {
  batchPagination.pageIndex = page;
  fetchBatchList();
};

const handleBatchRowSelect = (row: any) => {
  selectedBatchRow.value = row;
};

const handleBatchConfirm = () => {
  if (currentBatchDetailIndex.value === null) {
    batchDialogVisible.value = false;
    return;
  }

  const batchRow = selectedBatchRow.value;
  if (!batchRow) {
    ElMessage.warning("请选择批次号");
    return;
  }

  const detail = formModel.detail[currentBatchDetailIndex.value];
  if (!detail) {
    ElMessage.error("无法定位当前明细，请重新打开批次选择");
    return;
  }

  detail.batchNo = batchRow.batchCode;
  if (batchRow.createTime) {
    detail.productionDate = formatBatchDate(batchRow.createTime);
  }
  if (batchRow.endTime) {
    detail.expiryDate = formatBatchDate(batchRow.endTime);
  }
  batchDialogVisible.value = false;
};

// 仓库相关函数
const normalizeWarehouseOption = (item: any) => ({
  id: item.id ?? item.Id ?? 0,
  name:
    item.warehousenmae ??
    item.warehousename ??
    item.warehouseName ??
    item.Warehousenmae ??
    item.name ??
    "",
  principal:
    item.principal ??
    item.Principal ??
    item.warehousePrincipal ??
    item.WarehousePrincipal ??
    "",
});

const normalizeReservoirOption = (item: any) => ({
  id: item.id ?? item.Id ?? 0,
  name:
    item.reservoirnmae ??
    item.reservoirname ??
    item.Reservoirnmae ??
    item.name ??
    "",
  warehouseId: item.warehouseid ?? item.Warehouseid ?? item.warehouseId,
});

const normalizeSeatOption = (item: any) => ({
  id: item.id ?? item.Id ?? 0,
  name: item.seatnmae ?? item.seatname ?? item.Seatnmae ?? item.name ?? "",
  warehouseId: item.warehouseid ?? item.Warehouseid ?? item.warehouseId,
  reservoirId: item.reservoirid ?? item.Reservoirid ?? item.reservoirId,
});

const fetchWarehouseOptions = async () => {
  warehouseLoading.value = true;
  try {
    const params: Record<string, any> = {
      Pageindex: 1,
      PageSize: 1000,
      Warehousenmae: warehouseSearchForm.warehouse || undefined,
      WarehousenmaeLike: warehouseSearchForm.warehouse || undefined,
    };
    const res = await https.Reads.get("/Warehouse/WarehouseList", { params });
    const payload = res.data || {};
    const rawList = payload.data ?? payload.Data ?? [];
    warehouseOptions.value = Array.isArray(rawList)
      ? rawList.map((item: any) => normalizeWarehouseOption(item))
      : [];
  } catch (error) {
    console.error("获取仓库列表失败", error);
    warehouseOptions.value = [];
  } finally {
    warehouseLoading.value = false;
  }
};

const fetchReservoirOptions = async () => {
  reservoirLoading.value = true;
  try {
    const params: Record<string, any> = {
      Pageindex: 1,
      PageSize: 1000,
      Reservoirnmae: warehouseSearchForm.reservoir || undefined,
    };
    if (selectedWarehouseId.value) {
      params.Warehouseid = selectedWarehouseId.value;
    }
    const res = await https.Reads.get("/Warehouse/ReservoirList", { params });
    const payload = res.data || {};
    const rawList = payload.data ?? payload.Data ?? [];
    reservoirOptions.value = Array.isArray(rawList)
      ? rawList.map((item: any) => normalizeReservoirOption(item))
      : [];
  } catch (error) {
    console.error("获取库区列表失败", error);
    reservoirOptions.value = [];
  } finally {
    reservoirLoading.value = false;
  }
};

const fetchSeatOptions = async () => {
  seatLoading.value = true;
  try {
    const params: Record<string, any> = {
      Pageindex: 1,
      PageSize: 1000,
      Seatnmae: warehouseSearchForm.seat || undefined,
    };
    if (selectedWarehouseId.value) {
      params.Warehouseid = selectedWarehouseId.value;
    }
    if (selectedReservoirId.value) {
      params.Reservoirid = selectedReservoirId.value;
    }
    const res = await https.Reads.get("/Warehouse/Seatlist", { params });
    const payload = res.data || {};
    const rawList = payload.data ?? payload.Data ?? [];
    seatOptions.value = Array.isArray(rawList)
      ? rawList.map((item: any) => normalizeSeatOption(item))
      : [];
  } catch (error) {
    console.error("获取库位列表失败", error);
    seatOptions.value = [];
  } finally {
    seatLoading.value = false;
  }
};

const handleOpenWarehouseDialog = (detailIndex: number) => {
  currentWarehouseDetailIndex.value = detailIndex;
  warehouseDialogVisible.value = true;
  selectedWarehouseId.value = null;
  selectedReservoirId.value = null;
  selectedSeatId.value = null;
  selectedWarehouseOption.value = null;
  selectedReservoirOption.value = null;
  selectedSeatOption.value = null;
  warehouseSearchForm.warehouse = "";
  warehouseSearchForm.reservoir = "";
  warehouseSearchForm.seat = "";
  fetchWarehouseOptions();
  fetchReservoirOptions();
  fetchSeatOptions();
};

const handleWarehouseSearchSubmit = (
  type: "warehouse" | "reservoir" | "seat"
) => {
  if (type === "warehouse") {
    fetchWarehouseOptions();
  } else if (type === "reservoir") {
    fetchReservoirOptions();
  } else {
    fetchSeatOptions();
  }
};

const selectWarehouseOption = (option: any) => {
  selectedWarehouseId.value = option.id;
  selectedWarehouseOption.value = option;
  selectedReservoirId.value = null;
  selectedReservoirOption.value = null;
  selectedSeatId.value = null;
  selectedSeatOption.value = null;
  fetchReservoirOptions();
  fetchSeatOptions();
};

const selectReservoirOption = (option: any) => {
  selectedReservoirId.value = option.id;
  selectedReservoirOption.value = option;
  selectedSeatId.value = null;
  selectedSeatOption.value = null;
  fetchSeatOptions();
};

const selectSeatOption = (option: any) => {
  selectedSeatId.value = option.id;
  selectedSeatOption.value = option;
};

const handleWarehouseConfirm = () => {
  if (
    currentWarehouseDetailIndex.value === null ||
    !selectedWarehouseOption.value ||
    !selectedReservoirOption.value ||
    !selectedSeatOption.value
  ) {
    ElMessage.warning("请完整选择仓库、库区和库位");
    return;
  }
  const detail = formModel.detail[currentWarehouseDetailIndex.value];
  if (!detail) {
    ElMessage.error("无法定位当前明细，请重新打开仓库选择");
    return;
  }
  detail.warehouseName = `${selectedWarehouseOption.value.name} ${selectedReservoirOption.value.name} ${selectedSeatOption.value.name}`;
  detail.warehousePrincipal = selectedWarehouseOption.value.principal || "";
  warehouseDialogVisible.value = false;
};

onMounted(() => {
  initializeFromRoute();
});
</script>

<style scoped>
.product-storage-add-page {
  display: flex;
  flex-direction: column;
  gap: 20px;
  padding-bottom: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.breadcrumb-card {
  border-radius: 14px;
  background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
  border: none;
  color: #fff;
  box-shadow: 0 4px 12px rgba(106, 17, 203, 0.3);
}

.breadcrumb-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.breadcrumb-title {
  display: flex;
  align-items: center;
  gap: 16px;
}

.breadcrumb-icon {
  font-size: 32px;
  color: #fff;
}

.breadcrumb-heading {
  margin: 0;
  font-size: 22px;
  font-weight: 700;
}

.form-card {
  border-radius: 14px;
  border: none;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  background: #fff;
  padding-bottom: 16px;
}

.page-header {
  margin-bottom: 24px;
  border-bottom: 1px solid #f0f2f5;
  padding-bottom: 16px;
}

.page-header__content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 12px;
}

.page-header__title {
  display: flex;
  align-items: center;
  gap: 16px;
}

.page-header__icon-wrapper {
  width: 56px;
  height: 56px;
  border-radius: 16px;
  background: rgba(76, 161, 252, 0.15);
  display: flex;
  align-items: center;
  justify-content: center;
}

.page-header__icon {
  font-size: 28px;
  color: #4ca1fc;
}

.page-header__tag {
  display: flex;
  align-items: center;
  gap: 6px;
}

.form-section {
  border: 1px solid #f0f2f5;
  border-radius: 12px;
  padding: 24px 20px;
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header__main {
  display: flex;
  align-items: center;
  gap: 14px;
}

.section-header__icon {
  width: 44px;
  height: 44px;
  border-radius: 12px;
  background: rgba(76, 161, 252, 0.12);
  display: flex;
  align-items: center;
  justify-content: center;
  color: #4ca1fc;
}

.section-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.section-subtitle {
  margin: 2px 0 0 0;
  color: #909399;
}

.section-header__actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.system-code-field {
  display: flex;
  gap: 12px;
  align-items: center;
  flex-wrap: wrap;
}

.system-code-input {
  flex: 1;
  min-width: 200px;
}

.system-code-switch-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background: rgba(79, 172, 254, 0.06);
  border-radius: 8px;
  border: 1px solid rgba(79, 172, 254, 0.2);
  transition: all 0.3s ease;
}

.system-code-switch-wrapper:hover {
  background: rgba(79, 172, 254, 0.1);
  border-color: rgba(79, 172, 254, 0.3);
}

.switch-label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
  white-space: nowrap;
}

.system-code-switch {
  --el-switch-on-color: #4facfe;
}

.auto-generate-hint {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-top: 8px;
  padding: 6px 12px;
  background: rgba(79, 172, 254, 0.08);
  border-radius: 6px;
  font-size: 12px;
  color: #4facfe;
}

.hint-icon {
  font-size: 14px;
}

.detail-section {
  background: #fafbff;
  border-color: #e6ecff;
}

.product-type-select {
  width: 100%;
}

.product-type-dropdown {
  padding: 4px 0;
}

.product-type-option {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  color: #303133;
}

.product-type-option .dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: linear-gradient(135deg, #4facfe, #00f2fe);
  display: inline-block;
}

.product-type-dropdown .el-select-dropdown__item {
  padding: 10px 16px;
}

.product-type-dropdown .el-select-dropdown__item.hover {
  background: rgba(79, 172, 254, 0.08);
}

.detail-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.detail-item {
  background: #fff;
  border-radius: 12px;
  border: 1px solid #e6ecff;
  padding: 18px 16px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.04);
}

.detail-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.detail-item-number {
  font-weight: 600;
  color: #303133;
}

.detail-alert {
  margin-bottom: 16px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 8px;
}

.full-width {
  width: 100%;
}

.batch-select-field {
  display: flex;
  gap: 8px;
  align-items: center;
}

.batch-select-field .el-input {
  flex: 1;
}

.batch-select-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  font-weight: 500;
}

.warehouse-select-field {
  display: flex;
  gap: 8px;
  align-items: center;
}

.warehouse-select-field .el-input {
  flex: 1;
}

.warehouse-select-btn {
  display: flex;
  align-items: center;
  gap: 4px;
  font-weight: 500;
}

.batch-dialog-toolbar {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.batch-dialog-toolbar .el-input {
  flex: 1;
}

.batch-dialog-pagination {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

.warehouse-dialog-summary {
  margin-bottom: 12px;
  font-size: 14px;
  color: #606266;
}

.warehouse-dialog-columns {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}

.warehouse-column {
  border: 1px solid #ebeef5;
  border-radius: 10px;
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 12px;
  background: #fafbfc;
}

.column-title {
  font-weight: 600;
  color: #303133;
}

.column-list {
  max-height: 360px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  background: #fff;
}

.column-option {
  padding: 10px 12px;
  cursor: pointer;
  border-bottom: 1px solid #f2f3f5;
  transition: background 0.2s ease;
}

.column-option:last-child {
  border-bottom: none;
}

.column-option:hover {
  background: #f5f7fa;
}

.column-option.active {
  background: #ecf5ff;
  color: #409eff;
  font-weight: 600;
}

.column-search-icon {
  cursor: pointer;
}

.warehouse-dialog .el-empty {
  padding: 20px 0;
}
</style>
